package hongcaosp.app.android.video.online;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

import java.io.File;
import java.io.IOException;

public class VoiceUtil {

    private static MediaPlayer mediaPlayer;

    public static void play(String url,
                            MediaPlayer.OnPreparedListener onPreparedListener,
                            MediaPlayer.OnCompletionListener onCompletionListener,
                            MediaPlayer.OnErrorListener onErrorListener) throws IOException {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(onPreparedListener);
        mediaPlayer.setOnCompletionListener(onCompletionListener);
        mediaPlayer.setOnErrorListener(onErrorListener);
        mediaPlayer.setDataSource(url);
        mediaPlayer.prepare();
        mediaPlayer.start();
    }

    public static void play(Context context, File file,
                            MediaPlayer.OnPreparedListener onPreparedListener,
                            MediaPlayer.OnCompletionListener onCompletionListener,
                            MediaPlayer.OnErrorListener onErrorListener) throws IOException {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(onPreparedListener);
        mediaPlayer.setOnCompletionListener(onCompletionListener);
        mediaPlayer.setOnErrorListener(onErrorListener);
        mediaPlayer.setDataSource(context,Uri.fromFile(file));
        mediaPlayer.prepare();
        mediaPlayer.start();
    }

    public static void toggle() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            } else {
                mediaPlayer.start();
            }
        }
    }

    public static void release() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
